package databases

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"stforum/global"
	"stforum/global/model"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func StartBaseDataBases() (bool, error) {
	wd, _ := os.Getwd()
	i, err := GetBaseSettingInfo()
	if err != nil {
		return false, err
	}
	if i.Database == "sqlite3" {
		global.Logger.Info("正在连接sqlite3数据库：st.db")
		global.UserDB, err = gorm.Open(sqlite.Open(filepath.Join(wd, "st.db")))
		if err != nil {
			return false, err
		}
	}
	if i.Database == "mysql" {
		i_mysql, err := GetMysqlSettingInfo()
		if err != nil {
			return false, err
		}
		global.Logger.Info("正在连接mysql数据库：", i_mysql.Mysqldbname)
		build_mysql_info := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", i_mysql.Mysqlusername, i_mysql.Mysqlpassword, i_mysql.Mysqlhost, i_mysql.Mysqlport, i_mysql.Mysqldbname)
		global.Logger.Debug("构造登录数据串：", build_mysql_info)
		global.UserDB, err = gorm.Open(mysql.Open(build_mysql_info))
		if err != nil {
			return false, err
		}
	}
	migrateOk, m_err := AutoMigrateAll()
	if !migrateOk {
		global.Logger.Error("自动迁移数据库失败：", m_err.Error())
		return false, m_err
	}
	if i.Database != "sqlite3" && i.Database != "mysql" {
		return false, errors.New("未检出的数据库类型：" + i.Database)
	}
	return true, nil
}

func AutoMigrateAll() (bool, error) {
	err := global.UserDB.AutoMigrate(&model.UserTABLE{})
	if err != nil {
		return false, err
	}
	return true, nil
}
